#include "client.h"

int func_gets_client(int netfd){
    sleep(2);
    printf("初始化等待完成\n");
    char ff[5]={0};                                        
    recv(netfd,ff,5,0);
    if(ff[0]=='b')
    {
        printf("失败\n");
        return -1;
    }
    train_t train;
    char filename[100]={0};
    recvn(netfd, &train.length, sizeof(train.length));
    recvn(netfd, train.data, train.length);
    memcpy(filename,train.data,train.length);
    int fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0666);
    printf("收到文件名%s\n",filename);
    sleep(1);
    off_t filesize=0;
    recvn(netfd,&filesize,sizeof(off_t));
    printf("filesize = %ld\n", filesize);

    off_t cursize = 0;
    off_t lastsize = 0;
    off_t slice = filesize/10000;
    while(1) {
        if(cursize==filesize)break;
         recvn(netfd, &train.length, sizeof(train.length));
         if(train.length == 0) {
             break;
         }
         cursize += train.length;
         if(cursize - lastsize > slice) {
             printf("%5.2lf%%\r", 100.0*cursize/filesize);
             fflush(stdout);
             lastsize = cursize;
         }
         recvn(netfd, train.data, train.length);
         write(fd, train.data, train.length);
     }
     printf("success\n");
     close(fd);
     return 0;
}
